/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */

var levelOrder = function (root) {
    let res = []
    let queue = []
    let flag = 1
    if (!root) {
        return res
    }
    queue.push(root)
    while (queue.length) {
        let len = queue.length
        let ans = []
        while (len) {
            if (queue[0].left) {
                queue.push(queue[0].left)
            }
            if (queue[0].right) {
                queue.push(queue[0].right)
            }
            ans.push(queue[0].val)
            queue.shift()
            len--
        }
        // 根据层数来判定从左边还是从右边开始遍历 只需要翻转一下数组即可
        if(flag%2===1){
            res.push(ans)
        }
        if(flag%2===0){
            res.push(ans.reverse())
        }
        flag++
    }
    return res
};